package com.jar.exercise.网络编程.TCP连接.客服端和服务端;

import org.junit.Test;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * TCP连接，客户端发送信息，服务端读取  一次连接
 */
public class Demo1 {
	@Test
	public void client() throws IOException {
		//创建客户端的socket服务。指定目的主机和端口
		Socket socket = new Socket("192.168.234.1", 8888);
		//得到一个输出流
		OutputStream out = socket.getOutputStream();
		//写入内容
		out.write("张胜豪".getBytes());
		socket.close();
	}

	@Test
	public void server() throws IOException {
		ServerSocket serverSocket = new ServerSocket(8888);
		Socket socket = serverSocket.accept();
		InputStream input = socket.getInputStream();
		//不建议这样写，new byte[1024]长度不够可能会乱码，建议用ByteArrayOutputStream
       /* byte[] b = new byte[1024];
        int len;
        while ((len = input.read(b)) != -1) {
            String s = new String(b, 0, len);
            System.out.println("接收到来自"+socket.getInetAddress().getHostAddress()+"的信息："+s);
        }*/
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] b = new byte[3];
		int len;
		while ((len = input.read(b)) != -1) {
			out.write(b, 0, len);
		}
		System.out.println("接收到来自" + socket.getInetAddress().getHostAddress() + "的信息：" + out.toString());
		socket.close();
		serverSocket.close();
	}
}
